# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(ropls)
library(plyr)
library(magrittr)
library(optparse)
library(tidyverse)
library(ggrepel)
library(extrafont)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "Class_Color.txt", type = "character", help = "sample color file"),
  make_option("--pc", default = "", type = "character", help = "config file")

)
opt <- parse_args(OptionParser(option_list = option_list))
font_import(paths = c("/usr/share/fonts/myFonts"),recursive =F, prompt = F)

options(digits = 3)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/parse_config_json.R"))
baseFamily <- fontFamily

sampleColDf <- tibble(ClassNote = plotConfigJson$color$groups, col = plotConfigJson$color$colors)

sampleCols <- sampleColDf %>%
  deframe()

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote")) %>%
  mutate(ClassNote = as.character(ClassNote))

parent <- paste0("./")
createWhenNoExist(parent)
modeFileName <- paste0(parent, "/OPLSDA_R2X_R2Y_Q2.csv")
dataFileName <- paste0(parent, "/OPLSDA_Score.csv")
pdfFileName <- paste0(parent, "/OPLSDA_Score_2D.pdf")
plotData <- read_csv(dataFileName) %>%
  rename(SampleID = X1) %>%
  inner_join(sampleInfo, by = c("SampleID")) %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote)))
modelDf <- read.csv(modeFileName, header = T, stringsAsFactors = F, comment.char = "", row.names = 1)

print("===")
print(modelDf)

plotData

print(modelDf)

p <- ggplot(plotData, mapping = aes(x = P1, y = O1, color = ClassNote, label = SampleID)) +
  xlab(paste0("P1 (", modelDf["P1", "R2X"] * 100, "%)")) +
  ylab(paste0("O1 (", modelDf["O1", "R2X"] * 100, "%)")) +
  theme_bw(base_size = 8.8, base_family = baseFamily) +
  theme(axis.text.x = element_text(size = 9, vjust = 0.5),
        axis.text.y = element_text(size = 8.8), legend.position = 'right',
        axis.title.y = element_text(size = 12), legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'),
        legend.text = element_text(size = 9), axis.title.x = element_text(size = 12),
        panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
  ) +
  #0 line
  geom_vline(aes(xintercept = 0), colour = "#BEBEBE", linetype = "solid") +
  geom_hline(aes(yintercept = 0), colour = "#BEBEBE", linetype = "solid") +
  #point
  geom_point(aes(colour = factor(ClassNote)), size = 4, stroke = 0)

p <- getBasicPlotArg(p)

if (showSample) {
  p <- p +
    geom_text_repel(segment.size = 0.2, size = 2, family = baseFamily)
}

if (showEllipse) {
  p <- p +
    stat_ellipse(aes(fill = ClassNote), colour = NA, size = 0.3, level = 0.95, type = "norm",
                 geom = "polygon", alpha = 0.1, show.legend = F) +
    scale_fill_manual("", values = sampleCols)
}

if (!is.na(legendTitle)) {
  p <- p +
    scale_colour_manual(legendTitle, values = sampleCols)
}else {
  p <- p +
    scale_colour_manual("", values = sampleCols)
}

ggsave(limitsize = FALSE, pdfFileName, p, width = width, height = height)




